package com.gmail.at.controller;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.gmail.at.form.StationGrid;
import com.gmail.at.model.Station;
import com.gmail.at.service.StationService;
import com.google.common.collect.Lists;

@RequestMapping("/stations")
@Controller
public class StationController {

	final Logger logger = LoggerFactory.getLogger(StationController.class);

	@Autowired
	private StationService stationService;

	@Autowired
	MessageSource messageSource;

	@RequestMapping(method = RequestMethod.GET)
	public String list(Model uiModel) {
		logger.info("Listing stations");
		Station station = new Station();
		uiModel.addAttribute("station", station);
		return "stations/list";
	}

	@RequestMapping(value = "/listgrid", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public StationGrid listGrid(
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "rows", required = false) Integer rows,
			@RequestParam(value = "sidx", required = false) String sortBy,
			@RequestParam(value = "sord", required = false) String order) {
		logger.info("Listing stations for grid with page: {}, rows: {}", page,
				rows);
		logger.info("Listing stations for grid with sort: {}, order: {}",
				sortBy, order);
		// Process order by
		Sort sort = null;
		String orderBy = sortBy;
		if (orderBy != null && order != null) {
			if (order.equals("desc")) {
				sort = new Sort(Sort.Direction.DESC, orderBy);
			} else
				sort = new Sort(Sort.Direction.ASC, orderBy);
		}
		PageRequest pageRequest = null;
		if (sort != null) {
			pageRequest = new PageRequest(page - 1, rows, sort);
		} else {
			pageRequest = new PageRequest(page - 1, rows);
		}
		Page<Station> stationPage = stationService.findAllByPage(pageRequest);
		StationGrid stationGrid = new StationGrid();
		stationGrid.setCurrentPage(stationPage.getNumber() + 1);
		stationGrid.setTotalPages(stationPage.getTotalPages());
		stationGrid.setTotalRecords(stationPage.getTotalElements());
		stationGrid.setStationData(Lists.newArrayList(stationPage.iterator()));
		return stationGrid;
	}

	@RequestMapping(value = "/{stationID}", params = "delete", method = RequestMethod.GET)
	public @ResponseBody String delete(@PathVariable("stationID") Integer id, Model uiModel) {
		return stationService.delete(id);
	}

	@RequestMapping(value = "/{stationID}", params = "form", method = RequestMethod.POST)
	public @ResponseBody String update(@Valid Station station, @PathVariable("stationID") Integer id, BindingResult bindingResult,
			Model uiModel, HttpServletRequest httpServletRequest,
			RedirectAttributes redirectAttributes, Locale locale) {
		logger.info("Updating stations");
		if (bindingResult.hasErrors()) {
			return "Invalid station information (check station name)";
		}
		Station temp = stationService.findById(id);
		if (temp != null) {
			if (temp.getStationName().equals(station.getStationName())) {
				return "ok";
			}
			temp.setStationName(station.getStationName());
			Station result = stationService.save(temp);
			if (result == null) {
				return "This station name already exists!";
			} else {
				return "ok";
			}
		} else {
			return "Station with this id wasn't found, update your list";
		}
	}

	@RequestMapping(method = RequestMethod.POST)
	public @ResponseBody
	String create(@Valid Station station, BindingResult bindingResult,
			Model uiModel, HttpServletRequest httpServletRequest,
			RedirectAttributes redirectAttributes, Locale locale) {
		logger.info("Creating station");
		if (bindingResult.hasErrors()) {
			return "Invalid station information (check station name)";
		}
		Station result = stationService.save(station);
		if (result == null) {
			return "This station name already exists!";
		} else {
			return "ok";
		}
	}

}
